package com.seestech.sell.common.utils;

import org.apache.log4j.Logger;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * Created by Administrator on 2017/2/7.
 */
public class ZipFileUtils {
    private static Logger logger = Logger.getLogger(ZipFileUtils.class);

    /**
     * 解压文件到指定目录
     * @param zipFile   zip文件路径
     * @param descDir   解压之后的路径
     * @author idiot
     */
    public static void unZipFiles(File zipFile, String descDir) {
        logger.debug("******************开始解压文件********************");
        generateFile(descDir);//保证目录存在
        ZipFile zip = null;
        try {
            zip = new ZipFile(zipFile, Charset.forName("gbk"));
            Enumeration<ZipEntry> zes = (Enumeration<ZipEntry>) zip.entries();
            while(zes.hasMoreElements()){
                ZipEntry entry = zes.nextElement();
                String zipEntryName = entry.getName();
                InputStream in = zip.getInputStream(entry);

                String filePath = (FileUtils.addPathSeparate(descDir) + zipEntryName).replaceAll("\\*", "/");
                //如果当前对象是文件  写入  否则就创建目录
                if(!entry.isDirectory()) {
                    //当前对象是文件  但是路径类似 aaa/bb.png之类的  需要先创建文件夹
                    if(zipEntryName.contains("/")){
                        String dirPath = zipEntryName.substring(0, zipEntryName.lastIndexOf("/"));
                        generateFile((FileUtils.addPathSeparate(descDir) + dirPath).replaceAll("\\*", "/"));
                    }
                    OutputStream out = new FileOutputStream(filePath);
                    byte[] buf1 = new byte[1024];
                    int len;
                    while ((len = in.read(buf1)) > 0) {
                        out.write(buf1, 0, len);
                    }
                    out.close();
                }else {
                    generateFile(filePath);
                }
                in.close();
            }
        }catch (IOException e){
            logger.error(e.getMessage(), e);
        }finally {
            try {
                if (zip != null)
                    zip.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        logger.debug("******************解压完毕********************");
    }


    /**
     * @param path
     * @return
     */
    public static void generateFile(String path){
        File file = new File(path);
        //判断文件路径是否存在  不存在就创建
        if(!file.exists()){
            file.mkdirs();
        }
    }


    public static void doCompress(String srcFile, String zipFile) throws Exception {
        doCompress(new File(srcFile), new File(zipFile));
    }

    /**
     * 文件压缩
     * @param srcFile  目录或者单个文件
     * @param destFile 压缩后的ZIP文件
     */
    @Deprecated
    public static void doCompress(File srcFile, File destFile) throws Exception {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destFile));
        recursiveComperss(srcFile, out, "");
    }

    @Deprecated
    public static void recursiveComperss(File srcFile, ZipOutputStream out, String path) throws IOException {
        if(srcFile.isDirectory()){
            File[] files = srcFile.listFiles();
            for(File file : files){
                if(file.isDirectory()){
                    doCompressDirectory(file, out, path);
                    String newPath = path + "/" + file.getName();
                    recursiveComperss(file, out, newPath);
                } else {
                    //如果不是目录，则进行压缩
                    doCompress(file, out, path);
                }
            }
        }else {
            doCompress(srcFile, out, path);
        }
    }

    /*public static void doCompress(String pathname, ZipOutputStream out) throws IOException{
        doCompress(new File(pathname), out);
    }*/

    @Deprecated
    public static void doCompress(File file, ZipOutputStream out, String path) throws IOException{
        if( file.exists() ){
            byte[] buffer = new byte[1024];
            FileInputStream fis = new FileInputStream(file);
            out.putNextEntry(new ZipEntry(path +"/"+ file.getName()));
            int len = 0 ;
            // 读取文件的内容,打包到zip文件
            while ((len = fis.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            out.flush();
            out.closeEntry();
            fis.close();
        }
    }

    @Deprecated
    public static void doCompressDirectory(File file, ZipOutputStream out, String path) throws IOException{
        if( file.exists() ){
            out.putNextEntry(new ZipEntry(path + "/" + file.getName()+"/"));
            out.flush();
            out.closeEntry();
        }
    }


    public static void main(String[] args) throws Exception {
        ZipFileUtils.doCompress(new File("D:\\people\\storage\\myColumns\\1496643645966"), new File("D:\\people\\storage\\myColumns\\1496643645966.zip"));
    }

}
